package com.cly.getway.filters;

import com.cly.common.properties.JwtProperties;
import com.cly.common.util.JwtUtil;
import com.cly.getway.config.AuthProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.core.Ordered;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.function.Consumer;

@Component
public class JwtGlobalFilter implements GlobalFilter, Ordered{

    @Autowired
    private AuthProperties authProperties;

    @Autowired
    private JwtProperties jwtProperties;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher(); //  路径匹配器
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求
        ServerHttpRequest request = exchange.getRequest();
        // 判断是不是需要拦截的路径
        if(isExcludePath(request.getPath().toString())){
            // 包含在放行路径中
            return chain.filter(exchange);
        }

        // 获取请求头
        String token = null;
        List<String> authorization = request.getHeaders().get("Authorization");
        if(authorization != null && !authorization.isEmpty()){
            // 存在token
            token = authorization.get(0);
        }
        Long userId = null;
        try {
            userId = JwtUtil.parseToken(token, jwtProperties.getSecretKey());
        } catch (Exception e) {
            // token无效，设置响应码为401
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete(); // 响应结束
        }

        // 将用户信息设置到请求头，再进行请求转发
        String userInfo = userId.toString();
        ServerWebExchange serverWebExchange = exchange.mutate()
                .request(new Consumer<ServerHttpRequest.Builder>() {
                    @Override
                    public void accept(ServerHttpRequest.Builder builder) {
                        builder.header("user-info", userInfo);
                    }
                }).build();
        // 进行请求转发(放行)
        return chain.filter(serverWebExchange);
    }

    /**
     * 判断是否是排除路径
     * @param antPath
     * @return
     */
    private boolean isExcludePath(String antPath) {
        for (String path : authProperties.getExcludePaths()) {
            if (antPathMatcher.match(path, antPath)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
